//
//  MediaUtil.swift
//  GreenDeal
//
//  Created by Moennig Q on 2023/3/7.
//

import UIKit
import Photos

class MediaUtil: NSObject {
    //仿微信压缩图片大小，保持清晰度
    func resetSizeOfImageData(source_image: UIImage!,maxSize: Int = 300) -> NSData {
        //0.压缩质量为0.5，看是否符合要求
        let originalData = source_image.jpegData(compressionQuality: 0.5)!
        let originalSizeKB = originalData.count / 1024
        
        guard originalSizeKB > maxSize else {
            if APPConfig.isTestFlag {
                print("原始压缩系数是0.5的图片大小：\(originalSizeKB) KB")
            }
            return originalData as NSData
        }
        //1.不符合要求继续压缩尺寸
        var resultImage: UIImage = source_image
        //prepare constants
        let width = source_image.size.width
        let height = source_image.size.height
        let scale = width/height
        //设置默认size
        var sizeChange = source_image.size
        //1.获取压缩尺寸
        if width <= 1280 && height <= 1280{ //a，图片宽或者高均小于或等于1280时图片尺寸保持不变，不改变图片大小
            //            resultImage = source_image
        }else if width > 1280 || height > 1280 {//b,宽或者高大于1280，但是图片宽度高度比小于或等于2，则将图片宽或者高取大的等比压缩至1280
            
            if scale <= 2 && scale >= 1 {
                let changedWidth:CGFloat = 1280
                let changedheight:CGFloat = changedWidth / scale
                sizeChange = CGSize(width: changedWidth, height: changedheight)
                
            }else if scale >= 0.5 && scale <= 1 {
                
                let changedheight:CGFloat = 1280
                let changedWidth:CGFloat = changedheight * scale
                sizeChange = CGSize(width: changedWidth, height: changedheight)
                
            }else if width > 1280 && height > 1280 {//宽以及高均大于1280，但是图片宽高比大于2时，则宽或者高取小的等比压缩至1280
                
                if scale > 2 {//高的值比较小
                    
                    let changedheight:CGFloat = 1280
                    let changedWidth:CGFloat = changedheight * scale
                    sizeChange = CGSize(width: changedWidth, height: changedheight)
                    
                }else if scale < 0.5{//宽的值比较小
                    
                    let changedWidth:CGFloat = 1280
                    let changedheight:CGFloat = changedWidth / scale
                    sizeChange = CGSize(width: changedWidth, height: changedheight)
                    
                }
            }else {//d, 宽或者高，只有一个大于1280，并且宽高比超过2，不改变图片大小
                //                resultImage = source_image
            }
        }
        //2.根据新尺寸获取新图片
        if sizeChange.width > 0 && sizeChange.height > 0 {//size change必须为大于0的，否则renderer.image 返回的resultImage.images是空的，会导致resultImage.jpegData(compressionQuality: 0.5)! crash
            let format = UIGraphicsImageRendererFormat()
            format.opaque = false
            format.scale = UIScreen.main.scale
            let renderer = UIGraphicsImageRenderer(size: sizeChange,format: format)
            //，防止处理图片时内存暴涨
            resultImage = renderer.image { (context) in
                source_image.draw(in: CGRect(origin: .zero, size: sizeChange))
            }
        }
        //3.新图片.jpegData返回不为空，再次处理
        guard let data = resultImage.jpegData(compressionQuality: 0.5) else {
            return originalData as NSData
        }
        var resultImageData = data
        let sizeOriginKB    = resultImageData.count / 1024
        //
        if sizeOriginKB < maxSize{//小于maxsite
            DebugLog("重绘尺寸后压缩系数0.5原始图片大小：\(resultImageData.count / 1024) KB")
            return resultImageData as NSData
        }
        if sizeOriginKB > originalSizeKB {//重绘图片大于原始图片,用原图
            resultImage = source_image
        }
        
        var compressRatio: CGFloat = 0.5//0.5已经被压缩过了
        if sizeOriginKB > 1000 {
            compressRatio = 0.1
        }else if sizeOriginKB > 600 {
            compressRatio = 0.15
        }else if sizeOriginKB > 400 {
            compressRatio = 0.20
        }else if sizeOriginKB>300 && maxSize <= 300{
            compressRatio = 0.25
        }else if sizeOriginKB > 200 && maxSize <= 200{
            compressRatio = 0.3
        }else if sizeOriginKB > 100 && maxSize <= 100{
            compressRatio = 0.4
        }
        
        resultImageData = resultImage.jpegData(compressionQuality: compressRatio)!
        
        DebugLog("最后质量压缩系数为\(compressRatio)的图片大小：\(resultImageData.count / 1024) KB")
        return resultImageData as NSData
    }
    func getUIImage(asset: PHAsset) -> UIImage? {
        
        var img: UIImage?
        let manager = PHImageManager.default()
        let options = PHImageRequestOptions()
        options.version = .current //version with edits (aka adjustments) rendered or unadjusted version if there is no edits(如果被剪裁过就用就用剪裁过的图片，如果没有剪裁过就用原始图片)
        options.isSynchronous = true
        options.isNetworkAccessAllowed = true
        options.deliveryMode = .highQualityFormat//高质量图片
        manager.requestImage(for: asset, targetSize: PHImageManagerMaximumSize, contentMode: PHImageContentMode.aspectFit, options: options) { (resultImage, nil) in
            img = resultImage
        }
        return img
        
    }
    func getOrignalImageDataOfPHAsset(asset: PHAsset,  closure: @escaping ((NSData)->Void)) {
        
        let manager = PHImageManager.default()
        let options = PHImageRequestOptions()
        options.version = .current //version with edits (aka adjustments) rendered or unadjusted version if there is no edits(如果被剪裁过就用就用剪裁过的图片，如果没有剪裁过就用原始图片)
        options.isSynchronous = true
        options.isNetworkAccessAllowed = true
        options.deliveryMode = .highQualityFormat//高质量图片
        if #available(iOS 13, *) {
            manager.requestImageDataAndOrientation(for: asset, options: options) { data, _ , _ , _ in
                if let _ = data{
                    closure(NSData(data: data!))
                }
                
            }
        }else{
            manager.requestImageData(for: asset, options: options) { data, _, _, _ in
                if let _ = data{
                    closure(NSData(data: data!))
                }
            }
        }
        
    }
    //在屏幕上画图，已经考虑的图片的方向，即竖向
    func normalizedImage(_ data: Data)-> Data {
        guard let image = UIImage(data: data) else {
            return data
        }
        if image.imageOrientation == .up {
            return data
        }else{
            let newSize = CGSize(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)//image.size
            let renderer = UIGraphicsImageRenderer(size: newSize)
            //此方法比UIGraphicsBeginImageContextWithOptions好，防止处理图片时内存暴涨
            let resultImage = renderer.image { (context) in
                image.draw(in: CGRect(origin: .zero, size: newSize))
            }
            if let convertData = resultImage.jpegData(compressionQuality: 0.1){
                return convertData
            }else{
                return data
            }
        }
    }
    //播放声音
    func playSound(_ audioFileName: String) {
        if let url = Bundle.main.url(forResource: audioFileName, withExtension:nil){
            var soundId: SystemSoundID = 0
            AudioServicesCreateSystemSoundID(url as CFURL, &soundId)
            AudioServicesPlayAlertSound(soundId)
        }
    }
}
